﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace calcul
{
    public class ExpressionEvaluator
    {
        public double Evaluate(string expression)
        {
            // 移除空白字符  
            expression = expression.Replace(" ", "");

            // 分割字符串为操作数和操作符  
            List<double> numbers = new List<double>();
            List<char> operators = new List<char>();
            int i = 0;
            while (i < expression.Length)
            {
                if (char.IsDigit(expression[i]))
                {
                    // 读取完整的数字  
                    double number = 0;
                    while (i < expression.Length && char.IsDigit(expression[i]))
                    {
                        number = number * 10 + (expression[i] - '0');
                        i++;
                    }
                    numbers.Add(number);
                }
                else if (expression[i] == '+' || expression[i] == '-' || expression[i] == '*' || expression[i] == '/')
                {
                    operators.Add(expression[i]);
                    i++;
                }
                else
                {
                    throw new InvalidOperationException("Invalid character in expression: " + expression[i]);
                }
            }

            // 处理操作数和操作符  
            Stack<double> stack = new Stack<double>();
            foreach (double num in numbers)
            {
                stack.Push(num);
            }

            foreach (char op in operators)
            {
                double val2 = stack.Pop();
                double val1 = stack.Pop();
                switch (op)
                {
                    case '+': stack.Push(val1 + val2); break;
                    case '-': stack.Push(val1 - val2); break;
                    case '*': stack.Push(val1 * val2); break;
                    case '/':
                        if (val2 != 0)
                        {
                            stack.Push(val1 / val2);
                        }
                        else
                        {
                            throw new DivideByZeroException("Division by zero is not allowed!");
                        }
                        break;
                }
            }

            // 栈中应该只剩下一个元素，即最终结果  
            return stack.Pop();
        }
    }
}